package com.maddox.relax.bluetooth

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.maddox.relax.R
import com.maddox.relax.databinding.ActivityBluetoothClientBinding
import com.maddox.relax.util.LogUtil
import java.util.*

/**
 * @author Maddox
 * 蓝牙客户端  用于向服务端发送接收数据
 */
@SuppressLint("all")
class BluetoothClientActivity : AppCompatActivity() {


    lateinit var bluetoothAdapter: BluetoothAdapter
    lateinit var bluetoothDevice: BluetoothDevice
    private lateinit var connectThread: ConnectThread
    private lateinit var bluetoothService: MyBluetoothService

    lateinit var bd:ActivityBluetoothClientBinding

    private val handler: Handler by lazy {
        object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when (msg.what) {
                    MyBluetoothService.MESSAGE_READ -> {
                        val byteLength = msg.arg1
                        val bytes: ByteArray = msg.obj as ByteArray
                        val resultStr = String(bytes, 0, byteLength)
                        val preText = bd.getContent.text
                        bd.getContent.text = "$preText\n$resultStr"
                    }
                    MyBluetoothService.MESSAGE_WRITE -> {
                        Toast.makeText(this@BluetoothClientActivity, "发送数据成功", Toast.LENGTH_SHORT)
                            .show()
                    }
                    MyBluetoothService.MESSAGE_TOAST -> {
                        val tip = msg.data.getString("toast")
                        Toast.makeText(this@BluetoothClientActivity, tip, Toast.LENGTH_SHORT).show()
                    }
                }

            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bd = DataBindingUtil.setContentView(this,R.layout.activity_bluetooth_client)
        initView()
    }

    private fun initView() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        bluetoothDevice = intent.getParcelableExtra("device") as BluetoothDevice
        bd.send.setOnClickListener {
            val inputData = bd.inputContent.text.toString().trim().toByteArray()
            bluetoothService.sendData(inputData)
        }
        //建立连接
        bluetoothService = MyBluetoothService(handler)
        connectThread = ConnectThread(bluetoothDevice)
        connectThread.start()

    }


    //进行连接蓝牙设备的线程
    private inner class ConnectThread(val device: BluetoothDevice) : Thread() {

        private val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
            //构建连接
            device.createRfcommSocketToServiceRecord(UUID.fromString(BluetoothServerActivity.SERVICE_NAME))
        }

        override fun run() {
            mmSocket.let { socket->
                try {
                    socket?.connect()
                    LogUtil.d("连接蓝牙设备成功:${bluetoothDevice.name}")

                    //管理连接
                    manageMyConnectSocket(socket)
                } catch (e: Exception) {
                    LogUtil.d("连接异常:${e.message}")
                }
            }
        }

        //初始化数据交互MyBluetoothService
        private fun manageMyConnectSocket(socket: BluetoothSocket?) {
                bluetoothService.init(socket)
        }

        fun cancel() {
            try {
                bluetoothService.cancel()
            } catch (e: Exception) {
                LogUtil.d("无法关闭客户端连接")
            }

        }


    }


    private inner class MsgSendThread(val bluetoothService: MyBluetoothService?,val byteArray: ByteArray) : Thread() {

        override fun run() {
              bluetoothService?.sendData(byteArray)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        connectThread?.cancel()
    }


}